package com.ycl.javacore.rpctest.remote;

import com.ycl.javacore.rpctest.config.ServiceConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/23
 * Time: 4:52 PM
 * Desc: 类描述
 */
public class NettyServer {
    private List<ServiceConfig> serviceConfigList;
    private Map<String, Method> interfaceMethods;

    public NettyServer(List<ServiceConfig> serviceConfigList, Map interfaceMethods) {
        this.serviceConfigList = serviceConfigList;
        this.interfaceMethods = interfaceMethods;
    }

    public int init(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer("$$".getBytes());
                        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024 * 1024, delimiter));
                        channel.pipeline().addLast(new StringDecoder());
                        channel.pipeline().addLast(new RpcInvokerHandler(serviceConfigList, interfaceMethods));
                    }
                });
        ChannelFuture sync = b.bind(port).sync();
        System.out.println("启动NettyServer，端口为：" + port);
        return port;
    }
}
